import { SiteConfig, useConfig } from '@/store/config';
import { WebSiteWithCategory } from '@/types/website';
import { TableProps } from 'ant-design-vue';
import { Spec, Option } from '../type';
import ConditionTable, { getMatchKey } from './conditionTable';
import { useRowActive } from '../useRowActive.ts';
import { withModifiers } from 'vue';
import { CheckCircleFilled } from '@ant-design/icons-vue';
import { event } from './event.ts';
import { fetchCategoryConditions } from '@/api/website/index.ts';

export default defineComponent({
  props: {
    websites: {
      type: Array as PropType<WebSiteWithCategory[]>,
    },
  },
  setup(props, { attrs }) {
    const { websites } = toRefs(props);
    const siteConfigs = ref<SiteConfig[]>([]);
    const { getSiteConfigs } = useConfig();
    const current = ref(0);
    onMounted(async () => {
      siteConfigs.value = await getSiteConfigs();
    });

    watchEffect(
      () => {
        if (websites.value?.length) {
          const website_code = websites.value[current.value].website_code;
          event.emit('changeKey', website_code);
        }
      },
      {
        flush: 'post',
      }
    );

    return () => (
      <a-col span={12} class="h-full">
        <a-tabs v-model:activeKey={current.value}>
          {websites.value?.map((item, index) => {
            return (
              <a-tab-pane
                key={index}
                tab={`${item.website_name}-${item.category_name}`}
              >
                <RightTable
                  website={item}
                  siteConfigs={siteConfigs.value}
                  {...attrs}
                />
              </a-tab-pane>
            );
          })}
        </a-tabs>
      </a-col>
    );
  },
});

const RightTable = defineComponent({
  props: {
    website: {
      type: Object as PropType<WebSiteWithCategory>,
    },
    siteConfigs: {
      type: Array as PropType<SiteConfig[]>,
      default: () => [],
    },
    tableCollection: {
      type: Object as PropType<ConditionTable>,
      default: () => ({}),
    },
    rowH: {
      type: Number,
      default: 0,
    },
  },
  setup(props) {
    const columns: TableProps['columns'] = [
      {
        title: '条件',
        dataIndex: 'spec_name',
        width: 150,
        customRender({ value, record }) {
          if (isRowUsed(record)) {
            return (
              <span>
                <CheckCircleFilled class="text-success" /> {value}
              </span>
            );
          }
          return value;
        },
        sorter: (a, b) => useSorter(a.spec_name, b.spec_name)
      },
      {
        title: '选项',
        dataIndex: 'spec_options',
        ellipsis: true,
        customRender({ value }) {
          return value.map(item => item.spec_option_name).join(',');
        },
      },
      {
        title: '操作',
        customRender({ record }: { record: Spec }) {
          return (
            <a-space>
              {!props.tableCollection.rows.length ? (
                <a-button type="link" disabled>
                  匹配条件
                </a-button>
              ) : (
                <a-popconfirm
                  title="选择匹配的搜索条件"
                  onConfirm={() => {
                    return new Promise((resolve, reject) => {
                      if (currentSelect.value.length) {
                        currentSelect.value.forEach(item => {
                          props.tableCollection.addMerge(item, {
                            website: {
                              website_code,
                              category_name,
                              category_path,
                              category_code,
                              condition_name: record.spec_name,
                              condition_code:
                                record.spec_code || record.spec_name,
                              options: specToOption(record),
                            },
                            condition_name: record.spec_name,
                            alias_name: record.spec_name,
                          });
                        });
                        resolve('ok');
                      } else {
                        message.error('请选择一个条件');
                        reject('cancel');
                      }
                      currentSelect.value = [];
                    });
                  }}
                  onCancel={() => (currentSelect.value = [])}
                  v-slots={{
                    description: () => (
                      <a-select
                        class="w-200px"
                        getPopupContainer={el => el.parentNode}
                        placeholder="请选择"
                        allowClear
                        showSearch
                        option-filter-prop="title"
                        mode="multiple"
                        value={currentSelect.value}
                        onChange={val => {
                          currentSelect.value = val;
                        }}
                      >
                        {props.tableCollection.rows.map(item => (
                          <a-select-option
                            value={item.alias_name || item.condition_name}
                            key={item.condition_name}
                            title={item.alias_name || item.condition_name}
                            disabled={item.matches.some(match => {
                              return (
                                match.condition_name == record.spec_name &&
                                match.condition_code == record.spec_code &&
                                match.category_code == category_code &&
                                match.category_name == category_name &&
                                match.category_path == category_path &&
                                match.website_code == website_code
                              );
                            })}
                          >
                            {/* 优先显示别名 */}
                            {item.alias_name || item.condition_name}
                          </a-select-option>
                        ))}
                      </a-select>
                    ),
                  }}
                >
                  <a-button
                    type="link"
                    onClick={withModifiers(() => {}, ['stop'])}
                  >
                    匹配条件
                  </a-button>
                </a-popconfirm>
              )}
              <a-button
                type="link"
                disabled={isDisable(record)}
                onClick={() => {
                  addConditions([record]);
                }}
              >
                生成新条件
              </a-button>
            </a-space>
          );
        },
        width: 200,
      },
    ];
    const currentSelect = ref<string[]>([]);

    const dataSource = ref([]);
    const loading = ref(true);
    const { website, siteConfigs } = toRefs(props);
    const {
      website_code,
      id: category_id,
      nav_breadcrumb: category_path,
      category_name,
      category_code,
    } = website.value!;
    const selectedRowKeys = ref<string[]>([]);
    const selectedRows = ref<Spec[]>([]);
    const onChange = (keys: string[], rows) => {
      selectedRowKeys.value = keys;
      selectedRows.value = rows;
    };
    const isRowUsed = (record: Spec) => {
      const { matchMap } = props.tableCollection.getMap;
      return matchMap.has(
        getMatchKey({
          website_code,
          category_name,
          category_path,
          option_name: record.spec_name,
          option_value: record.spec_code || record.spec_name,
        })
      );
    };
    const isDisable = (record: Spec) => {
      const { conditionMap, matchMap } = props.tableCollection.getMap;
      return (
        matchMap.has(
          getMatchKey({
            website_code,
            category_name,
            category_path,
            option_name: record.spec_name,
            option_value: record.spec_code || record.spec_name,
          })
        ) && conditionMap.has(record.spec_name)
      );
    };

    const specToOption = (spec: Spec): Option[] => {
      return spec.spec_options.map(spec => {
        return {
          option_name: spec.spec_option_name,
          option_code: spec.spec_option_value,
          option_value: spec.spec_option_value,
          image_url: spec.spec_option_img_url,
        };
      });
    };
    const addConditions = (selects: Spec[]) => {
      selects.map(item => {
        props.tableCollection.addCondition({
          condition_name: item.spec_name,
          alias_name: item.spec_name,
          website: {
            website_code,
            category_name,
            category_path,
            category_code,
            options: specToOption(item),
            condition_name: item.spec_name,
            condition_code: item.spec_code || item.spec_name,
          },
        });
      });
      selectedRows.value = [];
      selectedRowKeys.value = [];
    };
    const getDataSource = async () => {
      // const scriptId = await getSiteConfig(website_code, 'CONDITION_EXTRACT');
      // const res = await execute<string>(scriptId!, {
      //   website_code,
      //   category_id,
      // });
      const res = await fetchCategoryConditions({
        websiteCode: website_code,
        categoryId: category_id,
      });
      dataSource.value = parseJson(res.data, []);
      loading.value = false;
    };
    watchEffect(() => {
      if (siteConfigs.value.length) {
        getDataSource();
      }
    });

    const merge_name = ref<string>();
    return () => (
      <div>
        <a-space class="mb-4">
          <a-button
            type="primary"
            disabled={!selectedRowKeys.value.length}
            onClick={() => addConditions(selectedRows.value)}
          >
            生成新条件
          </a-button>
          {selectedRowKeys.value.length ? (
            <a-popconfirm
              title="选择条件"
              onConfirm={() => {
                if (!merge_name.value) {
                  message.warning('请选择一个条件');
                  return Promise.reject();
                }
                selectedRows.value.forEach(item => {
                  props.tableCollection.addMerge(merge_name.value!, {
                    website: {
                      website_code,
                      category_name,
                      category_path,
                      category_code,
                      condition_name: item.spec_name,
                      condition_code: item.spec_code || item.spec_name,
                      options: specToOption(item),
                    },
                    condition_name: item.spec_name,
                    alias_name: item.spec_name,
                  });
                });
                selectedRowKeys.value = [];
                selectedRows.value = [];
                merge_name.value = undefined;
              }}
              onCancel={() => {
                merge_name.value = undefined;
              }}
              v-slots={{
                description: () => (
                  <a-select
                    class="w-250px"
                    placeholder="请选择"
                    v-model:value={merge_name.value}
                    getPopupContainer={el => el.parentNode}
                    showSearch
                    option-filter-prop="title"
                  >
                    {props.tableCollection.rows.map(item => (
                      <a-select-option
                        value={item.alias_name || item.condition_name}
                        key={item.condition_name}
                        title={item.alias_name || item.condition_name}
                      >
                        {/* 优先显示别名 */}
                        {item.alias_name || item.condition_name}
                      </a-select-option>
                    ))}
                  </a-select>
                ),
              }}
            >
              <a-button type="primary">匹配条件</a-button>
            </a-popconfirm>
          ) : (
            <a-button type="primary" disabled>
              匹配条件
            </a-button>
          )}
          <a-button
            onClick={() => {
              if (website.value?.category_href) {
                window.open(website.value.category_href);
              }
            }}
          >
            查看源网站
          </a-button>
        </a-space>
        <a-table
          row-selection={{
            selectedRowKeys: selectedRowKeys.value,
            onChange,
          }}
          customRow={useRowActive(active => {
            const row = dataSource.value[active] as Spec;
            if (row && isRowUsed(row) && website.value) {
              event.emit('changeRow', {
                website_code,
                row: {
                  condition_name: row.spec_name,
                  condition_code: row.spec_code,
                  ...website.value,
                },
              });
            } else {
              event.emit('changeRow', { website_code });
            }
          })}
          pagination={false}
          bordered
          row-key="spec_code"
          size="small"
          columns={columns}
          data-source={dataSource.value}
          loading={loading.value}
          scroll={{ y: props.rowH - 150 }}
        ></a-table>
      </div>
    );
  },
});
